package com.skivingcloud.develop.controller;

import com.mybatisflex.core.paginate.Page;
import com.skivingcloud.admin.logutils.OperateLog;
import com.skivingcloud.admin.utils.CommonConstant;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import com.skivingcloud.develop.constants.DataBaseColumnType;
import com.skivingcloud.develop.entity.SysFormDesigner;
import com.skivingcloud.develop.service.SysFormDesignerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

/**
 * 表单设计表 控制层。
 *
 * @author skivingcloud
 * @since 2024-01-18
 */
@RestController
@Tag(name = "组件设计表接口")
@RequestMapping("/sysFormDesigner")
public class SysFormDesignerController {

    private static final Logger log = LoggerFactory.getLogger(SysFormDesignerController.class);

    @Value("${skivingcloud.datasource.dialect:'mysql'}")
    private String dialect;

    @Resource
    private SysFormDesignerService sysFormDesignerService;

    /**
     * 添加组件设计表。
     *
     * @param sysFormDesigner 组件设计表
     * @return {@code {code:0,message:"",data:true}} 添加成功，{@code {code:500,message:"",data:false}} 添加失败
     */
    @OperateLog(module="组件设计表", description = "新增组件设计表")
    @PostMapping("/save")
    @Operation(summary="保存组件设计表")
    @PreAuthorize("hasAuthority('sys:formDesigner:save')")
    public ReturnT<Boolean> save(@Validated @RequestBody @Parameter(description="组件设计表")SysFormDesigner sysFormDesigner) {
        try{
            sysFormDesigner.setId(UuidUtil.get32UUID());
            sysFormDesigner.setVersion(0L);
            if (StringUtils.isBlank(sysFormDesigner.getResStatus())) {
                sysFormDesigner.setResStatus(CommonConstant.COMMON_YES_OR_NO_NO);
            }
            return ReturnT.ok(sysFormDesignerService.save(sysFormDesigner));
        }catch(Exception e){
            log.error("新增组件设计表失败", e);
            return ReturnT.error("新增组件设计表失败");
        }
    }

    /**
     * 根据主键删除组件设计表。
     *
     * @param id 主键
     * @return {@code {code:0,message:"",data:true}} 删除成功，{@code {code:500,message:"",data:false}} 删除失败
     */
    @OperateLog(module="组件设计表", description = "删除组件设计表")
    @PostMapping("/remove/{id}")
    @Operation(summary="根据主键获取组件设计表")
    @PreAuthorize("hasAuthority('sys:formDesigner:remove')")
    public ReturnT<Boolean> remove(@PathVariable("id") @Parameter(description="组件设计表主键")Serializable id) {
        try{
            return ReturnT.ok(sysFormDesignerService.removeById(id));
        }catch(Exception e){
            log.error("删除组件设计表失败", e);
            return ReturnT.error("删除组件设计表失败");
        }
    }

    /**
     * 根据主键更新组件设计表。若源记录已发布则生成新记录
     *
     * @param sysFormDesigner 组件设计表
     * @return {@code {code:0,message:"",data:true}} 更新成功，{@code {code:500,message:"",data:false}} 更新失败
     */
    @OperateLog(module="组件设计表", description = "修改组件设计表")
    @PostMapping("/update")
    @Operation(summary="根据主键更新组件设计表")
    @PreAuthorize("hasAuthority('sys:formDesigner:update')")
    public ReturnT<Boolean> update(@Validated @RequestBody @Parameter(description="组件设计表主键")SysFormDesigner sysFormDesigner) {
        try{
            if (StringUtils.isBlank(sysFormDesigner.getResStatus())) {
                sysFormDesigner.setResStatus(CommonConstant.COMMON_YES_OR_NO_NO);
            }
            return ReturnT.ok(sysFormDesignerService.updateVersion(sysFormDesigner));
        }catch(Exception e){
            log.error("保存组件设计表失败", e);
            return ReturnT.error("保存组件设计表失败！");
        }
    }

    /**
     * 发布组件
     *
     * @param sysFormDesigner 组件设计表
     * @return {@code {code:0,message:"",data:true}} 更新成功，{@code {code:500,message:"",data:false}} 更新失败
     */
    @OperateLog(module="组件设计表", description = "修改组件设计表")
    @PostMapping("/release")
    @Operation(summary="发布组件设计信息")
    @PreAuthorize("hasAuthority('sys:formDesigner:release')")
    public ReturnT<Boolean> release(@RequestBody @Parameter(description="组件设计表主键")SysFormDesigner sysFormDesigner) {
        try{
            return ReturnT.ok(sysFormDesignerService.release(sysFormDesigner));
        }catch(Exception e){
            log.error("发布组件设计表失败", e);
            return ReturnT.error("发布组件设计表失败！");
        }
    }
    /**
     * 根据组件设计表主键获取详细信息。
     *
     * @param id 组件设计表主键
     * @return 组件设计表详情
     */
    @GetMapping("/getInfo/{id}")
    @Operation(summary="根据主键获取组件设计表")
    public ReturnT<SysFormDesigner> getInfo(@PathVariable("id") Serializable id) {
        return ReturnT.ok(sysFormDesignerService.getById(id));
    }

    /**
     * 分页查询组件设计表。
     *
     * @param parameter 分页对象
     * @return 分页对象
     */
    @PostMapping("/page")
    @Operation(summary="分页查询组件设计表")
    @PreAuthorize("hasAuthority('sys:formDesigner:page')")
    public ReturnT<Page<SysFormDesigner>> page(@RequestBody @Parameter(description="分页信息")PageParameter<SysFormDesigner> parameter) {
        Page<SysFormDesigner> page = sysFormDesignerService.queryByPage(parameter);
        return ReturnT.ok(page);
    }
    
    /**
     * 根据名称查询表单
     * @param sysFormDesigner 查询条件
     * @return 表单数据
     */
    @PostMapping("/getFormDesignerByNameLike")
    @Operation(summary="根据名称查询表单")
    public ReturnT<List<SysFormDesigner>> getFormDesignerByNameLike(@RequestBody SysFormDesigner sysFormDesigner){
        List<SysFormDesigner> list = sysFormDesignerService.getFormDesignerByNameLike(sysFormDesigner.getFormName());
        return ReturnT.ok(list);
    }

    /**
     * 根据编码获取最新版本已发布的组件信息。
     *
     * @param code 组件设计编码
     * @return 组件设计详情
     */
    @GetMapping("/getLatestInfoByCode/{code}")
    @Operation(summary="根据编码获取最新版本已发布的组件信息")
    public ReturnT<SysFormDesigner> getLatestInfoByCode(@PathVariable("code") String code) {
        return ReturnT.ok(sysFormDesignerService.getLatestInfoByCode(code));
    }

    /**
     * 获取数据库字段类型。
     *
     * @return 数据库字段类型
     */
    @GetMapping("/getDataBaseColumnTypes")
    @Operation(summary="获取数据库字段类型")
    public ReturnT<String[]> getDataBaseColumnTypes() {
        switch (dialect){
            case "mysql" -> {
                return ReturnT.ok(DataBaseColumnType.MYSQL);
            }
            case "postgresql" -> {
                return ReturnT.ok(DataBaseColumnType.PostgreSQL);
            }
            case "oracle" -> {
                return ReturnT.ok(DataBaseColumnType.ORACLE);
            }
            default -> {
                return ReturnT.error("未支持该数据库");
            }
        }
    }

}
